import { View } from "@tarojs/components";
import { useState, forwardRef, useImperativeHandle, useEffect } from "react";
import { AtRadio } from "taro-ui";
import "./index.less";

const listData = [
  {
    text: "内衣",
    val: 0,
    children: [],
  },
  {
    text: "上装",
    val: 1,
    children: [
      {
        text: "T恤",
        val: 10,
      },
      {
        text: "卫衣",
        val: 11,
      },
    ],
  },
  {
    text: "下装",
    val: 2,
    children: [
      {
        text: "牛仔裤",
        val: 20,
      },
      {
        text: "运动裤",
        val: 21,
      },
    ],
  },
];

type propsType = {
  curVal?: { val: number; text?: string };
};

type childType = {
  val: number;
  text: string;
};

type itemType = {
  children: Array<childType> | [];
};

const defaultVal = {
  curVal: { val: -1, text: "" },
};

function Category(props: propsType = defaultVal, ref) {
  const [curParent, setCurParent] = useState<number>(initCurParent());
  const [curVal, setCurVal] = useState(props?.curVal ?? { val: -1, text: "" });

  useEffect(() => {
    console.log(props?.curVal);
  }, [props])

  useImperativeHandle(ref, () => ({
    curVal,
  }));

  function initCurParent() {
    const s = props?.curVal?.val.toString().substring(0, 1);
    return s ? parseInt(s) : -1;
  }

  function clickParentRadio(v: childType & itemType) {
    if (v.children.length > 0) {
      setCurParent(v.val);
    } else {
      setCurVal({ val: v.val, text: v.text });
    }
  }

  return (
    <View className='category'>
      {listData.map((v, k) => {
        return (
          <>
            {/* 父级 */}
            <AtRadio
              options={[{ label: v.text, value: v.val, desc: "" }]}
              value={v.children.length == 0 ? curVal.val : -1}
              key={k}
              onClick={() => clickParentRadio(v)}
            />
            {/* 子级 */}
            {curParent == v.val &&
              v.children.map(({ text, val }, ck) => {
                return (
                  <AtRadio
                    options={[{ label: text, value: val, desc: "" }]}
                    value={curVal.val}
                    key={ck}
                    onClick={() => setCurVal({ val, text })}
                    className='list-item'
                  />
                );
              })}
          </>
        );
      })}
    </View>
  );
}

export default forwardRef(Category);
